<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="skillCertificateForm" :label-width="formLabelWidth" ref="skillCertificateFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="应聘者姓名" prop="candidateName">
              <el-input v-model="skillCertificateForm.candidateName" placeholder="请选择应聘者姓名" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findCandidate"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="证书名称" prop="certificateName">
              <el-input v-model="skillCertificateForm.certificateName" placeholder="请输入证书名称" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="颁发机构" prop="issuingAuthority">
              <el-input v-model="skillCertificateForm.issuingAuthority" placeholder="请输入颁发机构" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="颁发时间" prop="issueDate">
              <el-date-picker
                  v-model="skillCertificateForm.issueDate" type="date" placeholder="颁发时间" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="到期日期" prop="expiryDate">
              <el-date-picker
                  v-model="skillCertificateForm.expiryDate" type="date" placeholder="到期日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="candidateSelectorVisible" v-if="candidateSelectorVisible" title="应聘者基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <candidate-selector @candidate-selected-event="handleCandidateSelectedEvent">
      </candidate-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import skillCertificateApi from '@/api/skillCertificateApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {SkillCertificateForm} from "@/types/req/skillCertificateForm";
import type {Result} from '@/types/result'
import type {SkillCertificate} from "@/types/resp/skillCertificate";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import CandidateSelector from "@/views/candidate/CandidateSelector.vue";

const props = defineProps<Id>()
const skillCertificateFormRef = ref<FormInstance | null>(null);
const skillCertificateForm = reactive<SkillCertificateForm>({
  candidateId: 0,
  candidateName: '',
  certificateName: '',
  issuingAuthority: '',
  issueDate: '',
  expiryDate: '',
})
const candidateSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetSkillCertificateAddEvent'): void;
  (e: 'closeSkillCertificateAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  candidateName: [
    { required: true, message: '请输入应聘者姓名', trigger: 'blur' }
  ],
  certificateName: [
    { required: true, message: '请输入证书名称', trigger: 'blur' }
  ],
  issuingAuthority: [
    { required: true, message: '请输入颁发机构', trigger: 'blur' }
  ],
  issueDate: [
    { required: true, message: '请输入颁发时间', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initSkillCertificateFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initSkillCertificateFormById = async (id: number) => {
  const resp: Result<SkillCertificate> = await skillCertificateApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(skillCertificateForm, resp.data)
  }
}

const onReset = () => {
  if (skillCertificateFormRef.value) {
    skillCertificateFormRef.value.resetFields()
  }
  emit('resetSkillCertificateAddEvent')
}

const onSave = () => {
  if (!skillCertificateFormRef.value) {
    return
  }
  skillCertificateFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await skillCertificateApi.save(skillCertificateForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeSkillCertificateAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findCandidate = () => {
  candidateSelectorVisible.value = true
}

const handleCandidateSelectedEvent = (selectedCandidate: any) => {
  candidateSelectorVisible.value = false
  if (selectedCandidate && 'candidateId' in selectedCandidate && skillCertificateForm.candidateId !== selectedCandidate['candidateId']) {
    skillCertificateForm.candidateId = selectedCandidate['candidateId']
    skillCertificateForm.candidateName = selectedCandidate['candidateName']
  }
}

const onBack = () => {
  emit('closeSkillCertificateAddEvent')
}
</script>

<style lang="scss">
</style>
